﻿<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>WebSocket Chat</title>
    <script type="text/javascript" src="Scripts/jquery-2.1.1.min.js"></script>
</head>
<body>
    <span>UserId: </span><input type="number" id="userId" value="1" />
    <input type="button" value="Connect" id="btnConnect" />
    <input type="button" value="Disconnect" id="btnDisconnect" /><br />
    <input type="text" id="textInput" />
    <input type="button" value="Send" id="btnSend" /><br />
    <span id="spanStatus">(display)</span>

    <script type="text/javascript">
        var ws;
        var options = {
            wsURL: "ws://" + window.location.hostname + ":" + window.location.port + "/WS/chat.ashx"
        };
        $(function () {
            $("#btnConnect").click(function () {
                $("#spanStatus").text("connecting");
                ws = new WebSocket(options.wsURL + "?userId=" + $('#userId').val());
                ws.onopen = function (e) {
                    console.log(e);
                    $("#spanStatus").text("connected");
                };
                ws.onmessage = function (evt) {
                    if (evt.data == null)
                        return;
                    var msg = JSON.parse(evt.data);
                    $("#spanStatus").text("Msg from server: " + msg.Data);
                };
                ws.onerror = function (evt) {
                    $("#spanStatus").text(evt.message);
                };
                ws.onclose = function () {
                    $("#spanStatus").text("disconnected");
                };
            });
            $("#btnSend").click(function () {
                if (ws.readyState == WebSocket.OPEN) {
                    ws.send($("#textInput").val());
                }
                else {
                    $("#spanStatus").text("Connection is closed");
                }
            });
            $("#btnDisconnect").click(function () {
                ws.close();
            });
        });
    </script>
</body>
</html>